package api

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"jdfs2/internal/api/buckets"
	"jdfs2/internal/api/multipart"
	"jdfs2/internal/api/objects"
	"jdfs2/internal/auth"
	"jdfs2/internal/service"
)

// RegisterRoutes registers all S3 API routes with authentication middleware
func RegisterRoutes(r *gin.Engine) error {
	// Health check without auth
	r.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })

	signer := auth.NewSigner()
	s3svc := service.S3()

	// SigV4 middleware
	authn := func(c *gin.Context) {
		// 跳过 ping 端点
		if c.Request.URL.Path == "/ping" {
			return
		}
		if err := signer.Verify(c.Request); err != nil {
			c.String(http.StatusUnauthorized, err.Error())
			c.Abort()
			return
		}
	}

	api := r.Group("/")
	api.Use(authn)

	// Register route handlers by category
	buckets.RegisterRoutes(api, s3svc)
	objects.RegisterRoutes(api, s3svc)
	multipart.RegisterRoutes(api, s3svc)

	return nil
}
